<?php

namespace app\util;

use app\v309\model\Custom;
use Grafika\Grafika;
use PHPQRCode\Constants;
use PHPQRCode\QRcode;

/*
 * 文件类
 */
class File
{
    public $error = '';

    /*
     * 返回错误信息
     */
    public function getError()
    {
        return $this->error;
    }

    /*
     * 上传图片
     * \think\File $file
     */
    public function uploadImage($file, $folder)
    {
        $mode = config('appconfig.app_production');
        if ($mode) {
            $publicFolder = 'kkmimg';
        } else {
            $publicFolder = 'testkkmimg';
        }

        $savename = date('Ymd') . '/' . time() . substr(microtime(), 2, 4) . mt_rand(1000, 9999);
        $uploadInfo = $file->move(ROOT_PATH . '../' . $publicFolder . '/sv300/' . $folder, $savename);
        if ($uploadInfo) {
            return 'sv300/' . $folder . str_replace(DS, '/', $uploadInfo->getSaveName());
        } else {
            return false;
        }
    }

    /*
     * 上传多张图片
     * \think\File[] $files
     */
    public function uploadMutilImage($files, $folder, $store_id)
    {
        $mode = config('appconfig.app_production');
        if ($mode) {
            $publicFolder = 'kkmimg';
        } else {
            $publicFolder = 'testkkmimg';
        }

        $imgArray = [];

        foreach ($files as $key => $file) {
            $savename = date('Ymd') . '/' . $store_id . time() . $key . mt_rand(1000, 9999);
            $uploadInfo = $file->move(ROOT_PATH . '../' . $publicFolder . '/sv300/' . $folder, $savename);
            if ($uploadInfo) {
                $img = 'sv300/' . $folder . str_replace(DS, '/', $uploadInfo->getSaveName());
                array_push($imgArray, $img);
            }
        }

        return $imgArray;
    }

    /*
     * 删除图片
     * string $file
     */
    public function deleteImage($file)
    {
        $mode = config('appconfig.app_production');
        if ($mode) {
            $publicFolder = 'kkmimg';
        } else {
            $publicFolder = 'testkkmimg';
        }

        $file = ROOT_PATH . '../' . $publicFolder . '/' . $file;
        if (is_file($file)) {
            return unlink($file);
        } else {
            return true;
        }
    }

    /*
     * 重命名图片
     */
    public function renameImg($oldname, $newname)
    {
        $mode = config('appconfig.app_production');
        if ($mode) {
            $publicFolder = 'kkmimg';
        } else {
            $publicFolder = 'testkkmimg';
        }

        $oldname = ROOT_PATH . '../' . $publicFolder . '/' . $oldname;
        $newname = ROOT_PATH . '../' . $publicFolder . '/' . $newname;

        return rename($oldname, $newname);
    }

    /*
     * 检查图片
     */
    public function checkImg($file)
    {
        if ($file->checkImg()) {
            if ($file->checkExt(['jpg', 'jpeg', 'png'])) {
                if ($file->checkSize(1048576)) {
                    return true;
                } else {
                    $this->error = '图片太大啦，上传失败';
                    return false;
                }
            } else {
                $this->error = '图片格式错误，只能上传jpg、jpeg和png图片';
                return false;
            }
        } else {
            $this->error = '非法图像文件';
            return false;
        }
    }

    /*
     * 生成店铺二维码
     */
    public function generateQrcode($store_id)
    {
        $mode = config('appconfig.app_production');
        if ($mode) {
            $publicFolder = 'kkmimg';
        } else {
            $publicFolder = 'testkkmimg';
        }

        $url = 'http://app.dwkkm.com/kkmtest/public/index/index/sweepcode/id/' . $store_id;

        QRcode::png($url, ROOT_PATH . '../' . $publicFolder . '/sv300/qrcode/' . $store_id . '.png', Constants::QR_ECLEVEL_L, 4, 1);
        
        $file = 'sv300/qrcode/' . $store_id . '.png';
        $urlpath = pathinfo($file, PATHINFO_DIRNAME);
        $imgUrl = self::getImageRealPath($file);
        $imgMessage = self::curlUploadImage($publicFolder,$urlpath,0,$imgUrl);
        return 'sv300/qrcode/' . $store_id . '.png';
    }

    /*
     * 生成店铺小程序码
     */
    public function generateXcxcode($store_id)
    {
        $mode = config('appconfig.app_production');
        if ($mode) {
            $publicFolder = 'kkmimg';
        } else {
            $publicFolder = 'testkkmimg';
        }

        $response = WxApp::getAccessToken();
        $result = json_decode($response, true);
        $access_token = $result['access_token'];

        $data = [
            'scene' => $store_id,
            'page' => 'pages/home/home',
            'width' => 200,
            'is_hyaline' => false,
        ];
        $coderesult = WxApp::getwxacode($access_token, json_encode($data));

        $xcxcode = 'sv300/xcxcode/' . $store_id . '.png';
        $path = ROOT_PATH . '../' . $publicFolder . '/' . $xcxcode;
        file_put_contents($path, $coderesult);

        $realPhoto = self::getImageRealPath($xcxcode);
        $curlPhoto = self::curlUploadImage($publicFolder, pathinfo($xcxcode, PATHINFO_DIRNAME), false, $realPhoto);

        if ($curlPhoto) {
            return $curlPhoto['image'];
        } else {

        }
    }

    /*
     * 返回单张图片缩略图
     * string $file
     */
    public function thumbImage($file)
    {
        $mode = config('appconfig.app_production');
        if ($mode) {
            $publicFolder = 'kkmimg';
        } else {
            $publicFolder = 'testkkmimg';
        }

        $editor = Grafika::createEditor();

        $pathinfo = pathinfo($file);
        $dirname = $pathinfo['dirname'];
        $basename = $pathinfo['basename'];

        $thumbFile = $dirname . '/thumb_' . $basename;

        $file = ROOT_PATH . '../' . $publicFolder . '/' . $file;
        $saveFile = ROOT_PATH . '../' . $publicFolder . '/' . $thumbFile;

        $editor->open($image, $file);
        $editor->resizeFill($image, 200, 200);
        $editor->save($image, $saveFile);

        return $thumbFile;
    }

    /*
     * 返回多张图片缩略图
     * array $files
     */
    public function thumbMutilImage($files)
    {
        $mode = config('appconfig.app_production');
        if ($mode) {
            $publicFolder = 'kkmimg';
        } else {
            $publicFolder = 'testkkmimg';
        }

        $thumbFiles = [];

        $editor = Grafika::createEditor();

        foreach ($files as $file) {
            $pathinfo = pathinfo($file);
            $dirname = $pathinfo['dirname'];
            $basename = $pathinfo['basename'];

            $thumbFile = $dirname . '/thumb_' . $basename;

            $file = ROOT_PATH . '../' . $publicFolder . '/' . $file;
            $saveFile = ROOT_PATH . '../' . $publicFolder . '/' . $thumbFile;

            $editor->open($image, $file);
            $editor->resizeFill($image, 200, 200);
            $editor->save($image, $saveFile);

            array_push($thumbFiles, $thumbFile);
        }

        return $thumbFiles;
    }

    /*
     * 本地保存第三方登录图片
     */
    public function getImage($url)
    {
        $mode = config('appconfig.app_production');
        if ($mode) {
            $publicFolder = 'kkmimg';
        } else {
            $publicFolder = 'testkkmimg';
        }

        $baseDir = 'sv300/custom/' . date('Ymd');

        $dir = ROOT_PATH . '../' . $publicFolder . '/' . $baseDir;
        //$savename = $baseDir . '/' . time() . substr(microtime(), 2, 4) . mt_rand(1000, 9999) . '.' . $extension;
        $savename = $baseDir . '/' . time() . substr(microtime(), 2, 4) . mt_rand(1000, 9999) . '.jpg';
        $filename = ROOT_PATH . '../' . $publicFolder . '/' . $savename;

        if (!file_exists($dir)) {
            mkdir($dir, 0755, true);
        }

        $image = file_get_contents($url);
        $result = file_put_contents($filename, $image);
        if ($result) {
            return $savename;
        } else {
            return Custom::DEFAULT_PHOTO;
        }
    }

    /*
     * 压缩图片
     */
    public function pressImage($file)
    {
        $mode = config('appconfig.app_production');
        if ($mode) {
            $publicFolder = 'kkmimg';
        } else {
            $publicFolder = 'testkkmimg';
        }

        $oldFile = ROOT_PATH . '../' . $publicFolder . '/' . $file;
        $newFile = $oldFile;

        $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        if ($extension == 'jpg' || $extension == 'jpeg') {
            $imagecreate = imagecreatefromjpeg($oldFile);
            imagejpeg($imagecreate, $newFile, 75);
            imagedestroy($imagecreate);
        } else if ($extension == 'png') {
            $imagecreate = imagecreatefrompng($oldFile);
            imagepng($imagecreate, $newFile, 9);
            imagedestroy($imagecreate);
        }

    }

    /*
     * curl上传图片
     * string $publicFolder 公共目录
     * string $folder 保存图片的路径
     * bool $thumb 是否生成缩略图
     * array $filename 图片名称
     */
    public function curlUploadImage($publicFolder, $folder, $thumb, $filename)
    {
        $url = 'http://47.104.83.107/thinkphp/public/index.php?s=index/curl/uploadimage';

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);

        $data = [
            'publicFolder' => $publicFolder,
            'folder' => $folder,
            'thumb' => $thumb,
        ];
        $data['image'] = new \CURLFile($filename);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $result = curl_exec($ch);

        if (curl_getinfo($ch, CURLINFO_HTTP_CODE) == 200) {
            curl_close($ch);
            return json_decode($result, true);
        } else {
            curl_close($ch);
            return false;
        }
    }

    /*
     * curl上传多张图片
     * string $publicFolder 公共目录
     * string $folder 保存图片的路径
     * bool $thumb 是否生成缩略图
     * array $filenames 数组，为一维数组，数组元素为图片名称
     */
    public function curlUploadMutilImage($publicFolder, $folder, $thumb, $filenames)
    {
        $url = 'http://47.104.83.107/thinkphp/public/index.php?s=index/curl/uploadmutilimage';

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);

        $data = [
            'publicFolder' => $publicFolder,
            'folder' => $folder,
            'thumb' => $thumb,
        ];
        for ($i = 0; $i < count($filenames); $i++) {
            $data['image_' . $i] = new \CURLFile($filenames[$i]);
        }
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $result = curl_exec($ch);

        if (curl_getinfo($ch, CURLINFO_HTTP_CODE) == 200) {
            curl_close($ch);
            return json_decode($result, true);
        } else {
            curl_close($ch);
            return false;
        }
    }

    /*
     * curl删除图片
     * string $publicFolder 公共目录
     * array $filename 图片名称
     */
    public function curlDeleteImage($publicFolder, $filename)
    {
        $url = 'http://47.104.83.107/thinkphp/public/index.php?s=index/curl/deleteimage';

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);

        $data = [
            'publicFolder' => $publicFolder,
            'filename' => $filename,
        ];
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $result = curl_exec($ch);
        if (curl_getinfo($ch, CURLINFO_HTTP_CODE) == 200) {
            curl_close($ch);
            return $result;
        } else {
            curl_close($ch);
            return false;
        }
    }

    /*
     * 获取单张图片真实路径
     */
    public function getImageRealPath($file)
    {
        $mode = config('appconfig.app_production');
        if ($mode) {
            $publicFolder = 'kkmimg';
        } else {
            $publicFolder = 'testkkmimg';
        }

        return ROOT_PATH . '../' . $publicFolder . '/' . $file;
    }

    /*
     * 获取多张图片真实路径
     */
    public function getMutilImageRealPath($array)
    {
        $mode = config('appconfig.app_production');
        if ($mode) {
            $publicFolder = 'kkmimg';
        } else {
            $publicFolder = 'testkkmimg';
        }

        foreach ($array as $key => $value) {
            $array[$key] = ROOT_PATH . '../' . $publicFolder . '/' . $value;
        }

        return $array;
    }

    
    /*
     * 生成预约确认二维码
     */
    public function generateCtmStaffQrcode($code)
    {
        $mode = config('appconfig.app_production');
        if ($mode) {
            $publicFolder = 'kkmimg';
        } else {
            $publicFolder = 'testkkmimg';
        }

        QRcode::png($code, ROOT_PATH . '../' . $publicFolder . '/sv300/ctmstaffqrcode/' . $code . '.png', Constants::QR_ECLEVEL_L, 4, 1);
        
        $file='sv300/ctmstaffqrcode/' . $code . '.png';
        $urlpath=pathinfo($file, PATHINFO_DIRNAME);
        $imgUrl=self::getImageRealPath($file);
        $imgMessage = self::curlUploadImage($publicFolder,$urlpath,0,$imgUrl);
        return 'sv300/ctmstaffqrcode/' . $code . '.png';
    }

     /*
     * 白色情人节生成图片(作废)
     */
//    public function WhiteDay($store_id,$num_id) {
//        $mode = config('appconfig.app_production');
//        if ($mode) {
//            $publicFolder = 'kkmimg';
//        } else {
//            $publicFolder = 'testkkmimg';
//        }
//        
//        $dst_im = ROOT_PATH ."../".$publicFolder."/sv300/whiteday/".$num_id.".jpeg";
//        $src_im = ROOT_PATH ."../".$publicFolder."/sv300/qrcode/".$store_id.".png";
// 
//        $dst = imagecreatefromstring(file_get_contents($dst_im));
//        $src = imagecreatefromstring(file_get_contents($src_im));
//        list($src_w, $src_h) = getimagesize($src_im);
//        //imagecopymerge($dst, $src, 10, 10, 0, 0, $src_w, $src_h, 50);
//        imagecopy($dst, $src, 150, 630, 0, 0, $src_w, $src_h);
//        
//        list($dst_w, $dst_h, $dst_type) = getimagesize($dst_im);
//        
//        $img_name = $store_id.'-'.$num_id;
//        switch ($dst_type) {
//            case 1://GIF
//                header('Content-Type: image/gif');
//                header('Content-Disposition: inline; filename="barcode.gif"');
//                imagegif($dst);
//                break;
//            case 2://JPG
//                header('Content-Type: image/jpeg');
//                header('Content-Disposition: inline; filename="barcode.jpg"');
//                imagejpeg($dst);
//                //imagejpeg($dst,ROOT_PATH . "../".$publicFolder."/sv300/whiteday/".$img_name.".jpeg");
//                
//                $file='sv300/whiteday/' . $img_name . '.jpeg';
//                $urlpath=pathinfo($file, PATHINFO_DIRNAME);
//                $imgUrl=self::getImageRealPath($file);
//                $imgMessage = self::curlUploadImage($publicFolder,$urlpath,0,$imgUrl);
//                break;
//            case 3://PNG
//                header('Content-Type: image/png');
//                header('Content-Disposition: inline; filename="barcode.png"');
//                imagepng($dst);
//                break;
//            default:
//                break;
//        }
//        imagedestroy($dst);
//        imagedestroy($src);
//    }
    
    /*
     * 白色情人节生成图片(作废)
     */
    public function whiteDay($store_id, $num_id)
    {
        $editor = Grafika::createEditor();

        $mode = config('appconfig.app_production');
        if ($mode) {
            $publicFolder = 'kkmimg';
        } else {
            $publicFolder = 'testkkmimg';
        }

        $img_name = $store_id . '-' . $num_id;

        $remoteFile = 'http://47.104.83.107/images/' . $publicFolder . '/sv300/qrcode/' . $store_id . '.png';
        $input2 = ROOT_PATH . '../' . $publicFolder . '/sv300/temp/' . $store_id . '.png';
        if (!file_exists($input2)) {
            $result = file_put_contents($input2, file_get_contents($remoteFile));
        } else {
            $result = true;
        }
        if ($result) {
            $input1 = ROOT_PATH . '../' . $publicFolder . '/sv300/whiteday/' . $num_id . '.png';
            //$input2 = ROOT_PATH . '../' . $publicFolder . '/sv300/qrcode/' . $store_id . '.png';
            $output = ROOT_PATH . '../' . $publicFolder . '/sv300/whiteday/' . $img_name . '.png';

            $image1 = Grafika::createImage($input1);
            $image2 = Grafika::createImage($input2);
            //$editor->resize($image2, 312, 312);
            $editor->blend($image1, $image2, 'normal', 1, 'top-left', 297, 1033);
            $editor->save($image1, $output);

            $file = 'sv300/whiteday/' . $img_name . '.png';
            $urlpath = pathinfo($file, PATHINFO_DIRNAME);
            $imgUrl = self::getImageRealPath($file);
            $imgResult = self::curlUploadImage($publicFolder, $urlpath,0, $imgUrl);
            if ($imgResult) {
                //unlink($input2);
            }
        }
    }
    /*
     *端午节活动二维码base64      
     */
    function getDragonBoatQrcode($url){
    $value = $url; //二维码内容
    $errorCorrectionLevel = 'L'; //容错级别
    $matrixPointSize = 5;//生成图片大小
    //生成二维码图片
    ob_start();
    QRcode::png($value,false,$errorCorrectionLevel, $matrixPointSize, 2);
    $imgstr = base64_encode(ob_get_contents());
    ob_end_clean();
    return $imgstr;
  }
  
  /*
     * 生成小程序码(项目详情、体验卡详情...)
     */
    public function generateXcxPagecode($scene,$page)
    {
        $response = WxApp::getAccessToken();
        $result = json_decode($response, true);
        $access_token = $result['access_token'];

//        $data = [
//            'path' => 'pages/home/projectDesc/projectDesc?item_id=7686&type=1&is_share=1',
//            'width' => 200,
//            'is_hyaline' => false,
//        ];
//        $postFields = json_encode($data);
//        $url = 'https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=' . $access_token;
//
//        $coderesult = Utils::curlSSLPost($url, $postFields);
        
        $data = [
            'scene' => $scene,
            'page' => $page,
            'width' => 200,
            'is_hyaline' => false,
        ];
        $coderesult = WxApp::getwxacode($access_token, json_encode($data));

        $imgstr = base64_encode($coderesult);
        return $imgstr;
    }

}